import {Command} from '../constant';
import Taro from '@tarojs/taro';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import {extraPathsValue} from '@/redux/util';
import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async page() {
      let uniqueID = Taro.getStorageSync('uniqueID');
      let itemStr = Taro.getStorageSync('b2b-wechat@login');
      if (itemStr) {
        action.findCustomerblacklist(itemStr.user.phone);
      }
      let params = {
        deviceNum: uniqueID,
      };
      let res = await api.forumController.getForumTitleList(params);
      if (res.success) {
        let titleList = [];
        res.data.map((item) => {
          let obj = {title: ''};
          obj.title = item.name;
          titleList.push(obj);
        });
        action.commonChange([
          {paths: 'main.tabList', value: res.data},
          {paths: 'main.titleList', value: titleList},
          {paths: 'main.selectId', value: res.data[0].id},
          {paths: 'main.current', value: 0},
          {paths: 'main.pageNum', value: 1},
        ]);
        //查询帖子信息
        this.getPosts();
      }
    },
    /**
     * 查询黑名单
     */
    async findCustomerblacklist(phone) {
      let result = await api.mobileConfigController.findCustomerblacklist({customerMobile: phone});
      Taro.setStorageSync('blacklistModel', result.content.length > 0 ? true : false);
      action.commonChange('main.blacklistModel', result.content.length > 0 ? true : false);
    },
    async getPosts() {
      let {selectId, pageNum, leftData: oldLeftData, rightData: oldRightData} = getData().main;
      let {user} = Taro.getStorageSync('b2b-wechat@login');
      let selectDistance = Taro.getStorageSync('selectDistance');
      let params = {
        pageNum,
        size: 5,
        userId: user?.id || '',
        type: '',
        scope: selectDistance.code,
        communityId: selectDistance.id,
        label: '',
        titleId: selectId,
      };
      let result = await api.forumController.getForumList(params);
      if (result.code == '200') {
        var rows = result.data.rows;
        // rows.forEach(item => {
        //   item.isMuti = true;
        // });
        // //数据性能优化
        // var listData = Object.values(rows.reduce((re, item) => {
        //   re[item.receiveTime] ? re[item.receiveTime].push(item) : re[item.receiveTime] = [item];
        //   return re;
        // }, {}));
        let leftData = [],
          rightData = [];
        for (let i = 0; i < rows.length; i++) {
          if (i % 2 == 0) {
            leftData.push(rows[i]);
          } else {
            rightData.push(rows[i]);
          }
        }
        if (pageNum == 1) {
          action.commonChange('main.leftData', leftData);
          action.commonChange('main.rightData', rightData);
          action.commonChange('main.totalPages', result.data.totalPage);
          return leftData.length != 0 && pageNum == result.data.totalPage;
        } else {
          // let newLeftData = oldLeftData.concat(leftData);
          // let newRightData = oldRightData.concat(rightData);
          // console.log(newLeftData, newRightData)
          action.commonChange('main.leftData', [...oldLeftData, ...leftData]);
          action.commonChange('main.rightData', [...oldRightData, ...rightData]);
          // leftData.forEach(e => {
          //   oldLeftData.push(e)
          // })
          // rightData.forEach(e => {
          //   oldRightData.push(e)
          // })
          action.commonChange('main.totalPages', result.data.totalPage);
          return [...oldLeftData, ...leftData].length != 0 && pageNum == result.data.totalPage;
        }
      }
    },
    async addThumb(params) {
      await api.forumController.addThumb(params);
    },
    async deleteThumb(params) {
      await api.forumController.deleteThumb(params);
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageCommunityMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
